<?php
App::import('Controller', 'SagePay.Payment');
App::import('Config', 'SagePay.sage_pay_settings');

class OrdersController extends StoreAppController {
    
	var $name = 'StoreOrders';
	var $permissions = array(
		'add' => array('admin','manag','users','firms'),
		'index' => array('admin','manag'),
		'edit' => array('admin','manag'),
		'delete' => array('admin','manag'),
		'view' => array('admin','manag','firms'),
		'account' => array('admin','manag','firms')
	);
	var $Payment;
	var $SagePaySettings;
	
	public function beforeFilter(){
		parent::beforeFilter();
		
		//Instantiation
    	$this->Payment =& new PaymentController();
    	//Load model, components...
    	$this->Payment->constructClasses();
    	$this->Payment->SagePaySettings =& new SagePaySettings();
    
     	App::import('Model', 'Store.store_product');
    	$this->StoreProduct =& new StoreProduct();
    	   	
    	App::import('Model', 'Store.store_product_types');
    	$this->StoreProductType =& new StoreProductType();
    	
//		$this->layout = 'cms';
	}
	
	function index() {
		$this->StoreOrder->recursive = 0;
		$this->set('storeOrders', $this->paginate());
	}
	
	function account($user_id=null) {
		if ($user_id != $this->Auth->user('id')) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect('/');
		}
		$this->StoreOrder->recursive = 0;
		$this->paginate = array('conditions'=>array('StoreOrder.user_id'=>$user_id));
		$this->set('storeOrders', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__d('store','Invalid store order', true));
			$this->redirect(array('action' => 'index'));
		}

		$this->StoreOrder->recursive = 2;
		
		$this->set('storeOrder', $this->StoreOrder->read(null, $id));
	}

	function add() {		
		if (!empty($this->data)) {
			if($this->_add_order()){
				
			} else {
				$this->Session->setFlash(__d('store','The  order could not be saved. Please, try again.', true));
				$this->redirect(array('plugin'=>'store','controller'=>'carts','action' => 'cart_view'));
			}
		}		
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__d('store','Invalid store order', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->StoreOrder->save($this->data)) {
				$this->Session->setFlash(__d('store','The store order has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__d('store','The store order could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->StoreOrder->read(null, $id);
		}
		$users = $this->StoreOrder->User->find('list');
		$this->set(compact('users'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__d('store','Invalid id for store order', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->StoreOrder->delete($id)) {
			$this->Session->setFlash(__d('store','Store order deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__d('store','Store order was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}

	
	
	function add_order(){
		if (!empty($this->data)) {
			if($this->_add_order()){
				if($this->_send()){							
					$this->Session->setFlash(__d("store","The store order has been send and saved", true));
					$this->Session->delete('Store.Cart');					
//					$this->redirect(array('plugin'=>'store','controller'=>'products','action'=>'display'));
				}else{
					$this->Session->setFlash(__d("store","The store order could not be sendd. Please, contact by phone or e-mail with store administrator.", true));
					$this->Session->delete('Store.Cart');
//					$this->redirect(array('plugin'=>'store','controller'=>'carts','action'=>'cart_view'));
				}				
			}					
		}	
	}
	
	function clear_basket(){		
        if ($this->RequestHandler->isAjax()) {			
				$this->_send();
		
				$this->Session->delete('Store.Cart');
				echo json_encode(array('cart'=>array(
					'save'=>'true',
					'error'=>'false',
					'message'=>null
					)));

			Configure::write('debug', 0);
			$this->autoRender = false;
			exit();
        }
	}
	
	private function _add_order(){
		$items = $this->Session->read('Store.Cart.Items');
		$delivery = $this->Session->read('Store.Cart.Delivery');
		
		$delivery_address = $this->Session->read('User.Customer.0');

		if (!empty($items) && is_array($items) && count($items) >= 1) {
			
			$this->transaction->begin($this);
			
			$this->data['StoreOrder']['user_id'] = $this->Auth->user('id');
			$this->data['StoreOrder']['added'] = date('Y-m-d H:i:s');
			if($delivery_address['delivery_as_billing'] != 1){
				$this->data['StoreOrder']['delivery_as_billing'] = 0;
				$this->data['StoreOrder']['delivery_name'] = $delivery_address['delivery_name'];
				$this->data['StoreOrder']['delivery_surname'] = $delivery_address['delivery_surname'];
				$this->data['StoreOrder']['delivery_address1'] = $delivery_address['delivery_address1'];
				$this->data['StoreOrder']['delivery_address2'] = $delivery_address['delivery_address2'];
				$this->data['StoreOrder']['delivery_address3'] = $delivery_address['delivery_address3'];
				$this->data['StoreOrder']['delivery_address4'] = $delivery_address['delivery_address4'];
				$this->data['StoreOrder']['delivery_address5'] = $delivery_address['delivery_address5'];
			}
			
			$this->StoreOrder->create();
			if ($this->StoreOrder->save($this->data)) {
				try{
					$order_id = $this->StoreOrder->getLastInsertID();
					$this->Session->write('Store.Cart.Order.id',$order_id);
					$this->Session->write('Store.Cart.Order.order_nout',$this->data['StoreOrder']['order_nout']);
					
					$this->data['StoreOrderDelivery']['order_id'] = $order_id;
					$this->data['StoreOrderDelivery']['name'] = $delivery['name'];
					$this->data['StoreOrderDelivery']['price'] = $delivery['price'];
					$this->data['StoreOrderDelivery']['currency_id'] = $delivery['currency_id'];
					$this->data['StoreOrderDelivery']['exchange'] = $delivery['exchange'];
					
					$this->StoreOrder->StoreOrderDelivery->create();
					$this->StoreOrder->StoreOrderDelivery->save($this->data);
					
					$this->data['StoreOrderDetail']['order_id'] = $order_id;					
					foreach ($items as $key => $item) {
						$this->data['StoreOrderDetail']['user_id'] = $this->Auth->user('id');
						$this->data['StoreOrderDetail']['product_id'] = $item['StoreProduct']['id'];
						$this->data['StoreOrderDetail']['currency_id'] = $item['StoreProduct']['currency_id'];
						
						$this->data['StoreOrderDetail']['tax_id'] = $item['StoreProduct']['tax_id'];
						$this->data['StoreOrderDetail']['unit_id'] = $item['StoreProduct']['unit_id'];
						$this->data['StoreOrderDetail']['exchange'] = $item['StoreCurrency']['exchange'];
						$this->data['StoreOrderDetail']['ilosc'] = $item['StoreProduct']['amount'];
						
						$service = $this->StoreProduct->field('StoreProduct.service',array('StoreProduct.id'=>$item['StoreProduct']['id']));
						
						if(isset($item['StoreType']) && !empty($item['StoreType'])){
							foreach ($item['StoreType'] as $type_id => $type){
								$this->data['StoreOrderDetail']['type_id'] = $type_id;
								
								$this->StoreOrder->StoreOrderDetail->create();
								if ($this->StoreOrder->StoreOrderDetail->save($this->data)){									
									
									$inventory = $this->StoreProductType->field('inventory',
											array('StoreProductType.product_id'=>$this->data['StoreOrderDetail']['product_id'],'StoreProductType.type_id'=>$type_id));
									if(!$service){				
										
										$inventory = $inventory - $item['StoreProduct']['amount'];
										$this->StoreProductType->query('UPDATE '.$this->StoreProductType->useTable.' SET inventory  = '.$inventory.' WHERE product_id = '.$item['StoreProduct']['id'].' AND type_id = '.$type_id  );
									}
								}else{									
									$this->transaction->rollback($this);
									return false;
								}
							}
								
							
							if(!$service){
								$stan = $this->StoreProduct->field('StoreProduct.stan',array('StoreProduct.id'=>$item['StoreProduct']['id']));
								$stan = $stan - $item['StoreProduct']['amount'];
								$this->StoreProduct->query('UPDATE '.$this->StoreProduct->useTable.' SET stan  = '.$stan.' WHERE id = '.$item['StoreProduct']['id'] );
							}	
													
						}else{
							$this->StoreOrder->StoreOrderDetail->create();
							if ($this->StoreOrder->StoreOrderDetail->save($this->data)){
								
								if(!$service){
									$stan = $this->StoreProduct->field('StoreProduct.stan',array('StoreProduct.id'=>$item['StoreProduct']['id']));	
									$stan = $stan - $item['StoreProduct']['amount'];
									$this->StoreProduct->query('UPDATE '.$this->StoreProduct->useTable.' SET stan  = '.$stan.' WHERE id = '.$item['StoreProduct']['id'] );
								}
							}
						}				
					}
				}catch (Exception $e){
					$this->transaction->rollback($this);
					return false;
				}
				
				$this->transaction->commit($this);
				return true;
			}
			$this->transaction->rollback($this);
			return false;
		}
	}
	
    private function _send(){
    	// adresy odbiorcow zamowienia
    	$manag = $this->User->find('list',array('fields'=>'email','conditions'=>array('User.group'=>"manag"))); // moderators
    	if(is_array($manag) && !empty($manag)){
    	}else{
    		$manag = $this->User->find('list',array('fields'=>'email','conditions'=>array('User.group'=>"admin")));
    	}
    	
        $sprzedawca = $this->User->find('first',array('conditions'=>array('User.group'=>"manag"))); // moderators
    	if(is_array($sprzedawca) && !empty($sprzedawca)){
    	}else{
    		$sprzedawca = $this->User->find('first',array('conditions'=>array('User.group'=>"admin")));
    	}    	
    	
    	// odbiorca
    	if($this->Session->check('Auth.User.id')){
			$customer = $this->Session->read('User.Customer.0');
			$employee = $this->Session->read('User.Employee.0');
			if(!is_array($customer) || empty($customer)){
				$customer = $employee;
			}
		}
    	
    	$items = $this->Session->read('Store.Cart.Items');
    	$delivery = $this->Session->read('Store.Cart.Delivery');
    	
    	
    	$ilosc_razem = 0;
		foreach ($items as $item) {				
			foreach ($item['StoreType'] as $type) {
				$ilosc_razem += $type['amount'];
			}
		}	    	
    	$this->set(compact('items','delivery','ilosc_razem','sprzedawca','customer'));
    	
//    	$this->Email->delivery = 'debug';
        $this->Email->to = $this->Session->read('Auth.User.email'); 
        $this->Email->bcc = $manag;
        $this->Email->subject = __d("store","Moon Jewellery Order ",true).$this->Session->read('Store.Cart.Order.id').' Confirmation'; 
        $this->Email->from = $_SERVER['HTTP_HOST']." <{$_SERVER['HTTP_HOST']}>"; 
        $this->Email->template = "plugin-store-order"; 
        $this->Email->sendAs = 'both'; // text; html; both;
 			
        //Do not pass any args to send() 
        if ( $this->Email->send() ) { 
             return true;
        } else { 
            return false; 
        }     
    }
    
    public function print_order($id=null){
    	$this->layout = 'print';
    	$order_id = $id;
    	// adresy odbiorcow zamowienia
    	$manag = $this->User->find('list',array('fields'=>'email','conditions'=>array('User.group'=>"manag"))); // moderators
    	if(is_array($manag) && !empty($manag)){
    	}else{
    		$manag = $this->User->find('list',array('fields'=>'email','conditions'=>array('User.group'=>"admin")));
    	}
    	
        $sprzedawca = $this->User->find('first',array('conditions'=>array('User.group'=>"manag"))); // moderators
    	if(is_array($sprzedawca) && !empty($sprzedawca)){
    	}else{
    		$sprzedawca = $this->User->find('first',array('conditions'=>array('User.group'=>"admin")));
    	}    	
    	
		
		
		$this->StoreOrder->recursive = 2;				
		$order = $this->StoreOrder->read(null, $id);
    	$delivery = $order['StoreOrderDelivery'][0];

        // odbiorca
    	if($this->Session->check('Auth.User.id')){
			$customer = (isset($order['User']['Customer'][0])) ? $order['User']['Customer'][0] : null;
			$employee = (isset($order['User']['Employee'][0])) ? $order['User']['Employee'][0] : null;
			if(!is_array($customer) || empty($customer)){
				$customer = $employee;
			}
		}
		

		if(!$order['StoreOrder']['delivery_as_billing']){
			$customer['delivery_as_billing'] = $order['StoreOrder']['delivery_as_billing'];
			$customer['delivery_name'] = $order['StoreOrder']['delivery_name'];
			$customer['delivery_surname'] = $order['StoreOrder']['delivery_surname'];
			$customer['delivery_address1'] = $order['StoreOrder']['delivery_address1'];
			$customer['delivery_address2'] = $order['StoreOrder']['delivery_address2'];
			$customer['delivery_address3'] = $order['StoreOrder']['delivery_address3'];
			$customer['delivery_address4'] = $order['StoreOrder']['delivery_address4'];
			$customer['delivery_address5'] = $order['StoreOrder']['delivery_address5'];
		}

    	$this->StoreProduct->recursive = 0;	
    	$ilosc_razem = 0;
    	$items = array();
    	$types = $this->StoreOrder->StoreType->find('list');
    	foreach ($order['StoreProduct'] as $key => $product) {
    		
    		$product_ = $this->StoreProduct->read(null, $product['id']);

    		$items[$product['id']]['StoreProduct'] = $product_['StoreProduct'];    	
   			$items[$product['id']]['StoreProduct']['amount'] = $product['StoreOrderDetail']['ilosc'];
   			$items[$product['id']]['StoreProduct']['price'] = $product['StoreOrderDetail']['price'];
   			$items[$product['id']]['StoreProduct']['currency_id'] = $product['StoreOrderDetail']['currency_id'];
   			$items[$product['id']]['StoreProduct']['exchange'] = $product['StoreOrderDetail']['exchange'];
  			$items[$product['id']]['StoreType'][$product['StoreOrderDetail']['type_id']]['name'] = $types[$product['StoreOrderDetail']['type_id']];
  			$items[$product['id']]['StoreCurrency'] = $product_['StoreCurrency'];
 			
   			$ilosc_razem += $product['StoreOrderDetail']['ilosc'];
    	}
		
    	$this->set(compact('items','delivery','ilosc_razem','sprzedawca','customer','order_id','order'));
    }

}
?>